package com.example.tnot.login.fragmentui;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.tnot.R;
import com.example.tnot.Student.DebugStudentActivity;
import com.example.tnot.Teacher.ActivityConfig.TeacherHomeActivity;
import com.example.tnot.Teacher.DebugTeacherActivity;
import com.example.tnot.Util.ToastUtil;
import com.example.tnot.api.HttpUtils;
import com.example.tnot.api.SocketClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class LoginFragment extends Fragment {

//    public static  final String BASE_URL ="http://10.30.7.70:8080/";
    public static  final String BASE_URL ="http://10.208.2.93:8080";

    private static final String LOGIN_URL = BASE_URL+"api/login";
    private static final String GET_DATA_URL = BASE_URL+"api/get_student_data";
    private static final String GET_TEACHER_URL = BASE_URL+"api/get_teacher_data";//
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

   // private static  SocketClient socketClient;
    public static JSONObject student_data = null;
    public static JSONObject teacher_data = null;
    private String mParam1;
    private String mParam2;
    //登录界面学生教师按钮
    TextView tv_teacher;
    TextView tv_test;
    TextView tv_student;
    //账号密码输入框
    EditText et_admin;
    EditText et_password;
    //身份认证按钮
    Button btn_login;
    ImageButton img_btn_back;
    TextView tv_mytoast;

    View mytoast_layout;
    //获取前一个Activity的bundle
    Boolean teacher_flag;
    LayoutInflater mytoast_inflater;
    View v = null;

    public LoginFragment() {
    }

    public static LoginFragment newInstance(String param1, String param2) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
//        socketClient = SocketClient.getInstance();
//        socketClient.connect();
//        while(!socketClient.getmSocket())
//        {;}
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_login, container, false);

        //初始化组件
        initViews();
        InitVar();
        //按用户分类初始化页面
        init();

        //测试按钮
        tv_test.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                getTeacherData("1001");//默认是王教授的账号
                Intent intent_test = new Intent(LoginFragment.this.getActivity(), TeacherHomeActivity.class);
                startActivity(intent_test);
                getActivity().finish();
                return false;
            }
        });

        //返回按钮
        img_btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = NavHostFragment.findNavController(LoginFragment.this);
                navController.navigate(R.id.action_loginFragment_to_identitySelectFragment);
            }
        });

        //学生教师登陆页面切换
        tv_teacher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SwitchTeacher();
            }
        });

        tv_student.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SwitchStudent();
            }
        });

        //身份验证（登录）
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String admin = et_admin.getText().toString();
                String password = et_password.getText().toString();
                Log.d("admin", admin);
                Log.d("password", password);

                if(admin.isEmpty() || password.isEmpty()){
                    showToast("账号或密码不能为空");
                    return;
                }

                //构建Json请求体
                HashMap<String, String> params = new HashMap<>();
                params.put("username", admin);
                params.put("password", password);
                String jsonData = HttpUtils.buildJsonString(params);

                String URL=LOGIN_URL;
                if(teacher_flag)
                    URL+="/2";
                else
                    URL+="/1";
                // 使用通用HTTP工具类发送登录请求
                HttpUtils.sendPostRequest(URL, jsonData, new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String response) throws JSONException {
                        handleLoginSuccess(response,admin);
                    }

                    @Override
                    public void onFailure(String errorMsg) {
                        handleLoginFailure(errorMsg);
                    }
                });
            }
        });
        return v;
    }

    private void getTeacherData(String id)
    {
        String URL=GET_TEACHER_URL +"/"+id;
        HttpUtils.sendGetRequest(URL, null, new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String response) throws JSONException {
                // 处理成功响应
                JSONArray  jsa=new JSONArray(response);
                teacher_data = jsa.getJSONObject(2).getJSONObject("data");
            }
            @Override
            public void onFailure(String errorMsg) {
                // 处理失败情况

                //showToast("ip地址更换或后台没开启，请联系后端人员");
               // Log.e("获取教师信息失败", errorMsg);
                Log.d("登陆界面(LOGIN)：获取教师信息失败", "ip地址更换或后台没开启，请联系后端人员");
            }
        });
    }

    private  void getStudentData(String id)
    {
        String URL=GET_DATA_URL +"/"+id;
        //Log.d("获取学生信息URL:",URL);
        HttpUtils.sendGetRequest(URL, null, new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String response) throws JSONException {
                // 处理成功响应
                JSONArray  jsa=new JSONArray(response);
                student_data = jsa.getJSONObject(2).getJSONObject("data");

            }

            @Override
            public void onFailure(String errorMsg) {
                // 处理失败情况
                Log.e("获取学生信息失败", errorMsg);
            }
        });
    }

    // 处理登录成功逻辑
    private void handleLoginSuccess(String response,String id) throws JSONException {
        // 确保在UI线程操作

        if (isAdded() && getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                try {
                    // 将响应字符串转换为JSON对象
                    JSONArray jsonArray = new JSONArray(response);

                    //Log.d("登陆请求","初始json"+jsonArray);
                    // 获取code字段（状态码）
                    int code = jsonArray.getJSONObject(0).getInt("code");
                    //Log.d("登陆请求","请求代码"+code);
                    // 根据code判断请求是否真正成功（200为成功）
                    if (code == 200) {


                        String data = jsonArray.getJSONObject(2).getString("data");


                        if (teacher_flag) {
                            showToast(data);
                            getTeacherData(id);
                            navigateToActivity(TeacherHomeActivity.class);
                            //
                            //navigateToActivity(TeacherHomeActivity.class);
                        } else {
                            getStudentData(id);
                            showToast(data);
                            navigateToActivity(DebugStudentActivity.class);
                        }

                    } else {
                        // 非200状态码：获取错误信息并提示
                        String message = jsonArray.getJSONObject(1).getString("status");
                        showToast(message);
                    }

                } catch (JSONException e) {
                    // JSON解析失败（格式错误等）
                    e.printStackTrace();
                    showToast("数据解析失败，请重试");
                }
            });
        }



    }

    // 处理登录失败逻辑
    private void handleLoginFailure(String errorMsg) {
        if (isAdded() && getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                showToast("登录失败: " + errorMsg);
            });
        }
    }

    // 跳转到指定Activity
    private void navigateToActivity(Class<?> targetActivity) {
        if (isAdded() && getActivity() != null) {
            Intent intent = new Intent(getActivity(), targetActivity);
            startActivity(intent);
            getActivity().finish();
        }
    }

    // 显示自定义Toast
// 替换原有的 showToast 方法
    private void showToast(String message) {
        if (isAdded() && getActivity() != null) {
            ToastUtil.showCustomToast(getActivity(), message);
        }
    }


    private void InitVar() {
        //获取flag参数
        teacher_flag = LoginFragmentArgs.fromBundle(requireArguments()).getFlag();
        Log.d("flag", String.valueOf(teacher_flag));

        //初始化 inflater
        mytoast_inflater = getLayoutInflater();

        //初始化自定义toast
        if (v != null) {
            mytoast_layout = mytoast_inflater.inflate(R.layout.mytoast_layout,
                    (ViewGroup) v.findViewById(R.id.mytoast_container));
            tv_mytoast = mytoast_layout.findViewById(R.id.tv_mytoast);
        }
    }

    //初始化控件（绑定控件）
    private void initViews() {
        if (v != null) {
            img_btn_back = v.findViewById(R.id.img_btn_back);
            tv_teacher = v.findViewById(R.id.tv_teacher);
            tv_student = v.findViewById(R.id.tv_student);
            et_admin = v.findViewById(R.id.et_admin);
            et_password = v.findViewById(R.id.et_password);
            btn_login = v.findViewById(R.id.btn_login);
            tv_test = v.findViewById(R.id.tv_test);
        }
    }

    //转变至教师用户登录的界面
    private void SwitchTeacher() {
        if (tv_student != null && tv_teacher != null && et_admin != null && btn_login != null) {
            tv_student.setBackgroundColor(0x1E1F22FF);
            tv_teacher.setBackgroundColor(0xFFFFFFFF);
            et_admin.setHint("工号/手机号");
            btn_login.setText("教师身份验证");
            teacher_flag = true;
            et_admin.setText("");
            et_password.setText("");
        }
    }

    //转变至学生用户登录界面
    private void SwitchStudent() {
        if (tv_student != null && tv_teacher != null && et_admin != null && btn_login != null) {
            tv_student.setBackgroundColor(0xFFFFFFFF);
            tv_teacher.setBackgroundColor(0x1E1F22FF);
            et_admin.setHint("学号/手机号");
            btn_login.setText("学生身份验证");
            et_admin.setText("");
            et_password.setText("");
            teacher_flag = false;
        }
    }

    //根据用户类型初始化界面
    private void init() {
        if (teacher_flag != null) {
            if (teacher_flag) {
                SwitchTeacher();
            } else {
                SwitchStudent();
            }
        }
    }
}
